import os.path

from celery import shared_task
from home.models import UserModel
from celery_app.celery import logger
from celery_app.config.logger_config import LOGS_PATH
from datetime import datetime

@shared_task(bind=True)
def add_func(self,a,b):
    for i in range(10):
        logger.info(f"定时任务开始执行（任务ID:{self.request.id}）,a+b+i={a+b+i}")

@shared_task(bind=True)
def ope_model(self):
    objs = UserModel.objects.all()
    for obj in objs:
        logger.info(f"异步任务开始执行（任务ID:{self.request.id}）,{obj.account}")

@shared_task(bind=True)
def rename_uwsgi_backup_log(self):
    # 将 根目录/logs中uwsgi.log.172384中的时间戳转成日期
    name_list = os.listdir(LOGS_PATH)
    name_pref = 'uwsgi.log.'
    task_id = f"任务ID={self.request.id}"
    for name in name_list:
        if name.startswith(name_pref):
            _,time_str = name.rsplit('.',1)
            try:
                time_int = int(time_str)
                date_str = datetime.fromtimestamp(int(time_int)).strftime("%Y-%m-%d_%H-%M-%S")
                new_name = f'{name_pref}{date_str}'
                old_path = os.path.join(LOGS_PATH,name)
                new_path = os.path.join(LOGS_PATH,new_name)
                if not os.path.exists(new_path):
                    os.rename(old_path,new_path)
                    logger.info(f'{task_id}，{name} 重命名成{new_name}')
                else:
                    for i in range(10):
                        new_name += f'-{i+1}'
                        new_path = os.path.join(LOGS_PATH,new_name)
                        if not os.path.exists(new_path):
                            os.rename(old_path, new_path)
                            logger.info(f'{task_id},{name} 重命名成{new_name}')
                            break
                    else:
                        logger.info(f"{task_id}，{name}进行10次重命名都失败了")
            except Exception as e:
                logger.error(f"{task_id},{name}重命名失败")